<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        div {
            position: absolute;
            width: 200px;
            height: 200px;
            background-color: pink;
        }
    </style>
</head>

<body>
    <button class="btn500">500</button>
    <button class="btn800">800</button>
    <div></div>
    <script>
        //获得元素
        var btn500 = document.querySelector('.btn500')
        var btn800 = document.querySelector('.btn800')
        var div = document.querySelector('div')
        function animate(obj, target, callback) {
            //防止用户多次点击，先清除一次定时器
            clearInterval(obj.timer)
            //设置定时器,把定时器添加为参数的属性，用于区分不同的定时器
            obj.timer = setInterval(function () {
                //缓动动画步长
                var tep = (target - obj.offsetLeft) / 10
                //步长可能为负数，进行取整
                tep = tep > 0 ? Math.ceil(tep) : Math.floor(tep)
                //如果到达目标值,则清除定时器，停止动画
                if (obj.offsetLeft == target) {
                    clearInterval(obj.timer)
                    //如果右回调函数，则执行回调函数
                    callback && callback()
                } else {
                    obj.style.left = obj.offsetLeft + tep + 'px'
                }
            }, 15)
        }   
        //点击事件
        btn500.addEventListener('click', function () {
            animate(div, 500)
        })
        btn800.addEventListener('click', function () {
            animate(div, 800)
        })
    </script>
</body>

</html>